package service

import (
	"context"
	"crypto/md5"
	"fmt"
	"io"
	"myuser/demo/dal/db"
	"myuser/demo/dal/model"
	errno "myuser/demo/error"
	"myuser/kitex_gen/demouser"
)

type CreateUserService struct {
	ctx context.Context
}

// NewCreateUserService new CreateUserService
func NewCreateUserService(ctx context.Context) *CreateUserService {
	return &CreateUserService{ctx: ctx}
}

func (s *CreateUserService) CreateUser(req *demouser.CreateUserRequest) error {
	users, err := db.QueryUser(s.ctx, req.Username)
	if err != nil {
		return err
	}
	if len(users) != 0 {
		return errno.UserAlreadyExistErr
	}
	//生成md5
	h := md5.New()
	if _, err = io.WriteString(h, req.Password); err != nil {
		return err
	}
	password := fmt.Sprintf("%x", h.Sum(nil))
	return db.CreateUser(s.ctx, []*model.User{{Username: req.Username, Avatar: password}})
}
